/* eslint-disable  */
import React from 'react';
import { ListView, List, SearchBar, ActivityIndicator } from 'antd-mobile';
import classnames from 'classnames';
import request from '@/utils/request';
import Icon from '../Icon';
import Popup from '../Popup';
import Empty from '../Empty';
import { itemMaps } from './util';
import './index.less';
const { Item } = List;
export interface IndexListProps {
  /**
   * todo
   * 没有写好
   */
  hasSearchBar: boolean;
  required?: boolean;
  title: string | JSX.Element;
  url?: string;
  payload?: string;
  placeholder?: string;
  header?: any;
  data?: any[];
  value?: number | string;
  // 数据源哪个字段当label
  keyName: 'label';
  // 数据源哪个字段当value
  valueName: 'value';
  cache?: boolean;

  onChange?: (value, item) => void;
}

interface State {
  visible: boolean;
  inputValue: any;
  dataSource: any;
  isLoading: boolean;
  value?: { label: string; value: string | number };
  onChange?: (value) => void;
}

class Index extends React.Component<IndexListProps, State> {
  constructor(props) {
    super(props);
    const getSectionData = (dataBlob, sectionID) => dataBlob[sectionID];
    const getRowData = (dataBlob, sectionID, rowID) => dataBlob[rowID];
    const dataSource = new ListView.DataSource({
      getRowData,
      getSectionHeaderData: getSectionData,
      rowHasChanged: (row1, row2) => row1 !== row2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
    });

    this.state = {
      visible: false,
      inputValue: '',
      dataSource,
      isLoading: true,
    };
  }
  componentDidUpdate(nextProps) {
    if (nextProps.value && !this.state.value) {
      this.setState({
        value: nextProps.value,
      });
      this.getDataSource(nextProps.value);
    }
  }
  cacheData = {};
  itemMaps = {};
  getDataSource = async (value?) => {
    const { url, payload, cache, data } = this.props;
    if (url) {
      const key = `${url}${JSON.stringify(payload)}`;
      if (cache && this.cacheData[key]) {
        return;
      }
      const data = await request(url, {
        method: 'POST',
        data: payload,
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded',
        // }
      });
      if (data.code === 0) {
        this.itemMaps = itemMaps(data.data);
        this.setState({
          dataSource: this.genData(this.state.dataSource, data.data),
        });
        this.cacheData[key] = true;
      }
    } else if (data) {
      this.itemMaps = itemMaps(data);
      this.setState({
        dataSource: this.genData(this.state.dataSource, data),
      });
    }
    if (value && this.itemMaps[value]) {
      this.setState({
        value: this.itemMaps[value],
      });
    }
    this.setState({
      isLoading: false,
    });
  };

  componentDidMount() {}
  genData = (ds, provinceData) => {
    const { keyName, valueName } = this.props;
    const dataBlob = {};
    const sectionIDs = [];
    const rowIDs = [];
    Object.keys(provinceData).forEach((item, index) => {
      sectionIDs.push(item);
      dataBlob[item] = item;
      rowIDs[index] = [];

      provinceData[item].forEach((jj) => {
        rowIDs[index].push(jj[valueName]);
        dataBlob[jj[valueName]] = jj;
      });
    });
    return ds.cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs);
  };

  onSearch = (val) => {
    // const pd = { ...province };
    // Object.keys(pd).forEach((item) => {
    //   const arr = pd[item].filter((jj) => jj.spell.toLocaleLowerCase().indexOf(val) > -1);
    //   if (!arr.length) {
    //     delete pd[item];
    //   } else {
    //     pd[item] = arr;
    //   }
    // });
    // this.setState({
    //   inputValue: val,
    //   dataSource: this.genData(this.state.dataSource, pd),
    // });
  };

  static defaultProps = {
    hasSearchBar: false,
    placeholder: '请选择',
    keyName: 'label',
    valueName: 'value',
    cache: false,
  };

  handleClick = () => {
    this.getDataSource();
    this.setState({
      visible: true,
    });
  };
  handleSelect = (item) => {
    const { onChange } = this.props;
    this.setState({
      visible: false,
      value: item,
    });
    if (typeof onChange === 'function') {
      onChange(item.value, item);
    }
  };
  render() {
    const { inputValue, dataSource, isLoading, visible, value } = this.state;
    const { hasSearchBar, required, title, placeholder, keyName, valueName } = this.props;
    const hasValue = value && value[keyName] ? true : false;
    return (
      <div className={classnames('hr-index-list')}>
        <List.Item
          arrow="horizontal"
          extra={
            <div className={classnames('hr-index-list-text', { placeholder: !hasValue })}>
              {hasValue ? value[keyName] : placeholder}
            </div>
          }
          onClick={this.handleClick}
        >
          {required && <span className="require-icon">*</span>}
          {title}
        </List.Item>
        <Popup
          className="hr-index-list-popup"
          visible={visible}
          title={title as string}
          okText="取消"
          dismissText=""
          onClose={() => this.setState({ visible: false })}
        >
          <div className="hr-index-list-main" key="hr-index-list-main">
            {hasSearchBar && (
              <SearchBar value={inputValue} placeholder="搜索" onChange={this.onSearch} />
            )}
            {isLoading ? (
              <div>
                <ActivityIndicator text="加载中..." className="hr-index-list-loading" />
              </div>
            ) : dataSource._dataBlob ? (
              <ListView.IndexedList
                dataSource={dataSource}
                className="am-list sticky-list"
                useBodyScroll={false}
                renderSectionHeader={(sectionData) => <div>{sectionData}</div>}
                renderRow={(rowData) => (
                  <Item
                    className="hr-index-list-row-item"
                    onClick={() => this.handleSelect(rowData)}
                  >
                    {rowData[keyName]}
                    {hasValue && rowData[valueName] === value[valueName] && (
                      <Icon type="iconxuanze" className="hr-index-list-row-item-selected" />
                    )}
                  </Item>
                )}
                quickSearchBarStyle={{
                  top: 170,
                }}
              />
            ) : (
              <Empty />
            )}
          </div>
        </Popup>
      </div>
    );
  }
}

export default Index;
